package com.egoo.ticket.server.utils.common;

import com.alibaba.fastjson.JSONObject;
import com.egoo.ticket.server.dao.EwsUserDao;
import com.egoo.ticket.server.dao.MsgTemplateMapper;
import com.egoo.ticket.server.dao.WorkOrderRelationMapper;
import com.egoo.ticket.server.pojo.dto.SystemMsgDto;
import com.egoo.ticket.server.pojo.entity.*;
import com.egoo.ticket.server.service.EripDataSynService;
import com.egoo.ticket.server.service.UserService;
import com.google.common.base.Splitter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class MsgUtil {
	@Autowired
	private EwsUserDao ewsUserDao;
	@Autowired
	private UserService userService;
	@Autowired
	private MsgTemplateMapper msgTemplateMapper;
	@Autowired
	private EripDataSynService eripDataSynService;
	@Autowired
	private WorkOrderRelationMapper workOrderRelationMapper;
	@Value("${server.client-phone-sign}")
	private String phoneNumber;

	public void getMsgCondition(String notifyType, List<MsgSettingRelation> msgSettingRelations, WorkOrder workOrder) {
		getMsgCondition(msgSettingRelations,workOrder);
	}

	private void getMsgCondition(List<MsgSettingRelation> msgSettingRelations, WorkOrder workOrder) {
		for (MsgSettingRelation msgSettingRelation:msgSettingRelations) {
			String msgTargetType = msgSettingRelation.getMsgTargetType();
			String msgType = msgSettingRelation.getMsgType();
			Integer msgTemplateId = msgSettingRelation.getMsgTemplateId();
			MsgTemplate msgTemplate = msgTemplateMapper.selectById(msgTemplateId);
			if (ObjectUtils.isEmpty(msgTemplate)){
				log.info("消息模板未设置:"+msgTemplate);
				continue;
			}

			List<EwsUser> ewsUsers = getSendTarget(msgTargetType, workOrder);
			if (CollectionUtils.isEmpty(ewsUsers)){
				log.info("用户信息不存在："+ewsUsers);
				continue;
			}

			if (ConstantCode.MsgType.MSG.equals(msgType)) {
				//发送短信
				log.info("此时开始发送短信");
				sendMsg(ewsUsers,msgTemplate,workOrder);
			}
			if (ConstantCode.MsgType.SYSTEM_MSG.equals(msgType)){
				//发送系统消息
				log.info("此时开始发系统消息");
				sendSysMsg(ewsUsers,msgTemplate,workOrder);
			}
			if (ConstantCode.MsgType.EMAIL.equals(msgType)){
				//发送邮件
				log.info("此时开始发邮件");
				sendEmail(ewsUsers,msgTemplate,workOrder);
			}
		}
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 获取目标接收人
	 * @Param:
	 * @return:
	 * @Date: 2020/11/3
	 */
	private List<EwsUser> getSendTarget(String msgTargetType, WorkOrder workOrder) {
		String tenantId = workOrder.getTenantId();
		String id = workOrder.getId();
		WorkOrderRelation workOrderRelation = new WorkOrderRelation();
		workOrderRelation.setWorkOrderId(id);
		workOrderRelation = workOrderRelationMapper.selectWorkOrderRelation(workOrderRelation);
		String targetStr = null;
		if (ConstantCode.MsgNotifyTarget.CREATOR.equals(msgTargetType)){
			targetStr = workOrder.getCreateUserId();
//			String createUserId = workOrder.getCreateUserId();
//			List<EwsUser> sendTarget = getSendTarget(targetStr, tenantId);
//			return sendTarget;
		}
		else if (ConstantCode.MsgNotifyTarget.HANDLER.equals(msgTargetType)){
			targetStr = workOrder.getCurrentHandlerId();
//			String currentHandlerId = workOrder.getCurrentHandlerId();
//			List<EwsUser> sendTarget = getSendTarget(targetStr, tenantId);
//			return sendTarget;
		}
		else if (ConstantCode.MsgNotifyTarget.Cc.equals(msgTargetType)){
			targetStr = workOrderRelation.getSender();
//			String sender = workOrderRelation.getSender();
//			List<EwsUser> sendTarget = getSendTarget(targetStr, tenantId);
//			return sendTarget;
		}
		else if (ConstantCode.MsgNotifyTarget.MONITOR.equals(msgTargetType)){
			targetStr = workOrderRelation.getWorkOrderMonitorId();
//			String workOrderMonitorId = workOrderRelation.getWorkOrderMonitorId();
//			List<EwsUser> sendTarget = getSendTarget(targetStr, tenantId);
//			return sendTarget;
		}
		else if (ConstantCode.MsgNotifyTarget.CUSTOMER.equals(msgTargetType)){
			JSONObject customField = workOrder.getCustomField();
			String phone = customField.getString(phoneNumber);
			EwsUser ewsUser = new EwsUser();
			ewsUser.setPhone(phone);
			ArrayList<EwsUser> sendTarget = new ArrayList<>();
			sendTarget.add(ewsUser);
			return sendTarget;
		}
		List<EwsUser> sendTarget = getSendTarget(targetStr, tenantId);
		return sendTarget;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 获取目标接收人;
	 * @Param:
	 * @return:
	 * @Date: 2020/11/3
	 */
	private List<EwsUser> getSendTarget(String idStr, String tenantId) {
//		List<String> list = Arrays.asList(idStr.split(","));
		List<String> list = Splitter.on(",").splitToList(idStr);
		Map<String, Object> hashMap = new HashMap<String, Object>(4);
		hashMap.put("userIds",list);
		hashMap.put("tenantId",tenantId);
		List<EwsUser> ewsUsers = ewsUserDao.selectAllUserList(hashMap);
		return ewsUsers;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 发送短信
	 * @Param:
	 * @return:
	 * @Date: 2020/11/3
	 */
	private void sendMsg(List<EwsUser> ewsUsers, MsgTemplate msgTemplate,WorkOrder workOrder) {
		String content = msgTemplate.getContent();
		content = contentHandle(content, workOrder);
		if (StringUtils.isEmpty(content)){
			log.info("此短信模板内容为空："+msgTemplate);
			return;
		}
		for (EwsUser ewsUser:ewsUsers) {
			if (StringUtils.isEmpty(ewsUser.getPhone())){
				log.info("此用户的电话信息不存在，请检查:"+ewsUser);
				continue;
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("phoneNumber",ewsUser.getPhone());
			jsonObject.put("content", content);
			jsonObject.put("tenantId",workOrder.getTenantId());
			jsonObject.put("userId",ConstantCode.SYSTEM_OPERATION_LOGO);
			jsonObject.put("msgTypeName","短信");
			jsonObject.put("workOrderId",workOrder.getId());
			log.info("此时开始调用erip发送短信");
			eripDataSynService.sendMsg(jsonObject);
		}
	}



	/**
	 * @Author: Donny_dong
	 * @Description: 发送系统消息
	 * @Param:
	 * @return:
	 * @Date: 2020/11/3
	 */
	private void sendSysMsg(List<EwsUser> ewsUsers, MsgTemplate msgTemplate, WorkOrder workOrder){
		String content = msgTemplate.getContent();
		content = contentHandle(content, workOrder);
		if (StringUtils.isEmpty(content)){
			log.info("此系统消息模板内容为空："+msgTemplate);
			return;
		}
		List<String> targetList = ewsUsers.stream().map(ewsUser -> ewsUser.getId()).collect(Collectors.toList());
		if (CollectionUtils.isEmpty(targetList)){
			log.info("系统消息目标接收人不存在:"+targetList);
			return;
		}

		SystemMsgDto<List> systemMsgDto = new SystemMsgDto<>();
		systemMsgDto.setTitle(msgTemplate.getName());
		systemMsgDto.setContent(content);
		systemMsgDto.setTargets(targetList);
		systemMsgDto.setSenderId(ConstantCode.SystemMsgConfig.SENDER_ID_SYS);
		systemMsgDto.setRemark(getRemark(workOrder.getId(),msgTemplate.getLinkToWorkOrder(),
				ConstantCode.SystemMsgConfig.WORK_ORDER));
		systemMsgDto.setTenantId(workOrder.getTenantId());
		log.info("此时开始调用erip发送系统消息:"+systemMsgDto);
		eripDataSynService.sendSystemMsg(systemMsgDto);
	}
	/**
	 * @Author: Donny_dong
	 * @Description: 获取系统消息remark
	 * @Param:
	 * @return:
	 * @Date: 2020/11/24
	 */
	private JSONObject getRemark(String id, String linkToWorkOrder, String workOrder) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put(ConstantCode.SystemMsgConfig.REMARK_ORDER_ID, id);
		jsonObject.put(ConstantCode.SystemMsgConfig.REMARK_IS_JUMP, linkToWorkOrder);
		jsonObject.put(ConstantCode.SystemMsgConfig.REMARK_SYSTEM_TYPE, workOrder);
		return jsonObject;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 发送邮件
	 * @Param:
	 * @return:
	 * @Date: 2020/11/3
	 */
	public void sendEmail(List<EwsUser> ewsUsers, MsgTemplate msgTemplate, WorkOrder workOrder){
		log.info("获取的消息模板msgTemplate:"+msgTemplate);
		String content = msgTemplate.getContent();
		content = contentHandle(content, workOrder);
		if (StringUtils.isEmpty(content)){
			log.info("邮件模板内容为空："+msgTemplate);
			return;
		}
		//邮件地址集合
		List<String> targetList = ewsUsers.stream().map(ewsUser -> ewsUser.getEmail()).collect(Collectors.toList());
		if (CollectionUtils.isEmpty(targetList)){
			log.info("邮件目标接收人不存在:"+targetList);
			return;
		}
		String title = contentHandle(msgTemplate.getTitle(), workOrder);
		log.info("转换后的邮件标题为:"+title);
		SystemMsgDto<List> systemMsgDto = new SystemMsgDto<>();
		WorkOrderRelation workOrderRelation = new WorkOrderRelation();
		workOrderRelation.setWorkOrderId(workOrder.getId());
		workOrderRelation = workOrderRelationMapper.selectWorkOrderRelation(workOrderRelation);
		systemMsgDto.setTenantId(workOrder.getTenantId());
		systemMsgDto.setSessionId(workOrderRelation.getSessionId());
		systemMsgDto.setTitle(title);
		systemMsgDto.setSenderId(workOrder.getCustomField().getString("CREATE_AGENTID"));
		systemMsgDto.setContent(content);
		systemMsgDto.setTargets(targetList);
		systemMsgDto.setAttachmentAdd(msgTemplate.getAttachmentAddress() == null?null:msgTemplate.getAttachmentAddress().toJSONString());
		systemMsgDto.setTemplateId(msgTemplate.getId() ==null?null:msgTemplate.getId().toString());
		log.info("此时开始调用erip发邮件");
		eripDataSynService.sendEmail(systemMsgDto);
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 替换模板中的占位参数
	 * @Param:
	 * @return:
	 * @Date: 2020/11/26
	 */
	public String contentHandle(String content, WorkOrder workOrder) {
		if (!content.contains("}")){
			log.info("无需要替换的参数，直接返回"+content);
			return content;
		}

		String[] contents = content.split("}");

		ArrayList<String> arrayList = new ArrayList<>();

		for (int i = 0; i <contents.length ; i++) {
			String item = contents[i];

			int a = item.indexOf("{");
			if (a < 0){
				continue;
			}
			String substring = item.substring(a+1);
			arrayList.add(substring);

		}
		content = contentHandle(content,arrayList,workOrder);
		log.info("占位参数转换的结果为："+content);
		return content;
	}

	private String contentHandle(String content, ArrayList<String> arrayList, WorkOrder workOrder) {
		if (CollectionUtils.isEmpty(arrayList)){
			log.info("没有要替换的参数直接返回"+content+"----"+arrayList);
			return content;
		}
		for (String str:arrayList
		) {
			String sour = "{"+str+"}";

			if (ConstantCode.MsgTemplateParam.WORK_ORDER_ID.equals(str)){
				str = workOrder.getId();
				content = content.replace(sour, str);
			}
			if (ConstantCode.MsgTemplateParam.BACK_NODE_HANDLER.equals(str)){
				List<String> list = Splitter.on(",").splitToList(workOrder.getHistoryHandlerId());
				str = list.get(list.size() - 1);
				content = content.replace(sour, str);
			}
			if (str.contains(ConstantCode.MsgTemplateParam.CUSTOM_FIELD_SUFFIX)){
				List<String> split = Splitter.on(".").splitToList(str);
				JSONObject customField = workOrder.getCustomField();
				str = customField.getString(split.get(1));
				if (!StringUtils.isEmpty(str)) {
					content = content.replace(sour, str);
				}
			}
		}
		return content;
	}
}
